//
//  XTComposeTextView+Extension.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/23.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

extension XTComposeTextView{
    //获取富文本对应的字符串
    var emoticonText:String{
        var result :String = ""
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            if let attachment = infoDic["NSAttachment"] as? XTTextAttachment{
            //此时为文本附件
                let chs = attachment.emoticon!.chs
                result += chs!
            }else{
            //此时为纯文本
                let text = self.attributedText.attributedSubstringFromRange(range).string
                result += text
            
            }
        }
        return result
   
    }
    
    
    //插入表情富文本
    func insertEmoticon(emoticon:XTEmoticon,font:UIFont){
        if emoticon.type == "0"{
        //图片表情
            //记录上一次的富文本
            var originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
            
            //1 根据表情图片路径创建出image
            let image = UIImage(named: emoticon.path!)
            //2 将图片转换为NSTextAttachment(文本附件)
            let attachment = XTTextAttachment()
            attachment.emoticon = emoticon
            attachment.image = image
            
            //*************这里需要获取高度
            //3 将NSTextAttachment（文本附件）转换为NSAttributedString（富文本）
            let attributedString = NSAttributedString(attachment: attachment)
            //获取当前textview的选中范围
            var range = self.selectedRange
            //替换选中的字符串 ？？？？***********
            originalAttr.replaceCharactersInRange(range, withAttributedString: attributedString)
            //设置富文本文字的大小
            originalAttr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, originalAttr.length))
            //设置富文本
            self.attributedText = originalAttr
            //每次点击的位置＋1
            range.location += 1
            //设置选中范围长度为0
            range.length = 0
            
            self.selectedRange = range
            //发送文字改变通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //自己使用代理监控
            self.delegate?.textViewDidChange?(self)
            
        }else{
        //emoji表情
            self.insertText((emoticon.code! as NSString).emoji())
        
        }
    
    }

}
